package com.andnux.android.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.andnux.android.MainApp;
import com.andnux.android.activity.ChatActivity;
import com.andnux.android.adapter.OnItemClickListener;
import com.andnux.android.adapter.SessionAdapter;
import com.andnux.android.data.ChatSession;
import com.andnux.android.data.PageData;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.data.Works;
import com.andnux.android.databinding.FragmentSessionBinding;
import com.andnux.android.databinding.ItemSessionBinding;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class SessionFragment extends BaseFragment<FragmentSessionBinding> {

    private int current = 0;
    private static final int size = 10;
    private SessionAdapter adapter;
    private final List<ChatSession> list = new ArrayList<>();
    private DesignCloudApi api;

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadData();
        }
    };

    @Override
    public void onViewCreated(View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter = new SessionAdapter();
        binding.content.setAdapter(adapter);
        api = RetrofitClient.getInstance().getServerApi();
        binding.smart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                current++;
                loadData();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                current = 0;
                loadData();
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener<ItemSessionBinding>() {
            @Override
            public void onItemClick(ItemSessionBinding view, int position, long id) {
                ChatSession session = list.get(position);
                addDisposable(api.worksDetail(Long.valueOf(session.getWorksId()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new NotNullConsumer<Result<Works>>() {
                            @Override
                            public void onSuccess(Result<Works> result) {
                                session.setWorks(result.getData());
                                Intent intent = new Intent(requireActivity(), ChatActivity.class);
                                intent.putExtra("session", session);
                                startActivity(intent);
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                binding.smart.finishLoadMoreWithNoMoreData();
                                binding.smart.finishRefresh();
                                if (throwable != null) {
                                    Toast.makeText(requireActivity(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }));
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction("message");
        requireActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        requireActivity().unregisterReceiver(receiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        SystemUsers users = MainApp.getApp().getSystemUsers();
        addDisposable(api.chatSessionPage(current, size,
                String.valueOf(users.getId()), null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<PageData<List<ChatSession>>>>() {
                    @Override
                    public void onSuccess(Result<PageData<List<ChatSession>>> result) {
                        if (current == 0) {
                            list.clear();
                        }
                        List<ChatSession> works = result.getData().getList();
                        list.addAll(works);
                        adapter.setNewData(list);
                        if (works.size() < size) {
                            binding.smart.finishLoadMoreWithNoMoreData();
                        } else {
                            binding.smart.finishLoadMore();
                        }
                        binding.smart.finishRefresh();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        binding.smart.finishLoadMoreWithNoMoreData();
                        binding.smart.finishRefresh();
                        if (throwable != null) {
                            Toast.makeText(requireActivity(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));

    }
}